<template>
    <li @mouseenter="mouseHandler(true)" @mouseleave="mouseHandler(false)"
        :style="{backgroundColor:bgColor,color:fnColor}">
        <label>
            <input type="checkbox" v-model="complete"/>
            <span>{{todo.title}}</span>
        </label>
        <button class="btn btn-danger" v-show="isShow" @click="deleteItem">删除</button>
    </li>
</template>

<script lang="ts">
    import {defineComponent, ref, computed} from 'vue';
    import {Todo} from "@/types/Todo";

    export default defineComponent({
        name: 'Item',
        props: {
            todo: {
                type: Object as () => Todo,
                required: true
            },
            deleteTodo: {
                type: Function,
                required: true
            },
            index: {
                type: Number,
                required: true
            },
            updateTodoComplete: {
                type: Function,
                required: true
            }
        },
        setup(props) {
            // 背景色
            const bgColor = ref('white')
            // 字体颜色
            const fnColor = ref('black')
            // 删除按钮的显示控制
            const isShow = ref(false)
            // 鼠标进入和离开事件的回调函数
            const mouseHandler = (flag: boolean) => {
                if (flag) {
                    // 鼠标进入
                    bgColor.value = 'pink'
                    fnColor.value = 'green'
                    isShow.value = true
                } else {
                    // 鼠标离开
                    bgColor.value = 'white'
                    fnColor.value = 'black'
                    isShow.value = false
                }
            }

            // 删除按钮
            const deleteItem = () => {
                if (window.confirm('确定删除吗?')) {
                    props.deleteTodo(props.index)
                }
            }

            // 使用计算属性来设置选中状态
            const complete = computed({
                get() {
                    return props.todo.isCompleted
                },
                set(val) {
                    props.updateTodoComplete(props.todo, val)
                }
            })
            return {
                mouseHandler,
                bgColor,
                fnColor,
                isShow,
                deleteItem,
                complete
            }
        }
    });
</script>

<style scoped>
    /*Item*/
    li {
        list-style: none;
        height: 36px;
        line-height: 36px;
        padding: 0 5px;
        border-bottom: 1px solid #ddd;
    }

    li label {
        float: left;
        cursor: pointer;
    }

    li label li input {
        vertical-align: middle;
        margin-right: 6px;
        position: relative;
        top: -1px;
    }

    li button {
        float: right;
        /*display: none;*/
        margin-top: 3px;
    }

    li:before {
        content: initial;
    }

    li:last-child {
        border-bottom: none;
    }

</style>